<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left back-icon" @click="goBack"></i>
      <p>商家信息</p>
    </header>
    <!-- 商家logo部分 -->
    <div class="merchant-logo">
      <img :src="business.businessImg" />
    </div>
    <!-- 商家信息部分 -->
    <div class="merchant-info">
      <h1>{{ business.businessName }}</h1>
      <p>
        &#165;{{ business.starPrice }}起送 &#165;{{
          business.deliveryPrice
        }}配送
      </p>
      <p>{{ business.businessExplain }}</p>
    </div>

    <!-- 添加食品按钮，仅商家可见 -->
    <button v-if="isMerchant" @click="addNewProduct">添加食品</button>

    <!-- 食品列表部分 -->
    <ul class="food">
      <li v-for="(item, index) in foodArr" :key="index">
        <div class="left">
          <img :src="item.foodImg" />
          <div class="left-info">
            <h3>{{ item.foodName }}</h3>
            <p>{{ item.foodExplain }}</p>
            <p>&#165;{{ item.foodPrice }}</p>
          </div>
        </div>
        <div class="right">
          <div>
            <i class="fa fa-minus-circle" @click="minus(index)" v-show="item.quantity != 0"></i>
          </div>
          <p>
            <span v-show="item.quantity != 0">{{ item.quantity }}</span>
          </p>
          <div>
            <i class="fa fa-plus-circle" @click="add(index)"></i>
          </div>
        </div>
        <!-- 只有商家可以看到的编辑和删除按钮 -->
        <button v-if="isMerchant" @click="editProduct(index)">编辑商品</button>
        <button v-if="isMerchant" @click="deleteProduct(item.foodId)">删除商品</button>
      </li>
    </ul>

    <!-- 编辑商品弹窗 -->
    <div v-if="showEditModal" class="edit-modal">
      <div class="modal-content">
        <h3>{{ isEditing ? '编辑商品' : '添加商品' }}</h3>
        <input v-model="currentEditItem.foodName" placeholder="商品名称">
        <input v-model="currentEditItem.foodPrice" placeholder="商品价格" type="number">
        <textarea v-model="currentEditItem.foodExplain" placeholder="商品描述"></textarea>
        <button @click="isEditing ? saveProduct() : saveNewProduct()">
          {{ isEditing ? '保存' : '添加' }}
        </button>
        <button @click="cancelEdit">取消</button>
      </div>
    </div>
    <!--推荐商家按钮-->
    <div class="merchant-button" @click="toBusinessInfo(commendId)">
      <button>
        <div class="button-left">
          <h3>推荐商家</h3>
        </div>
        <div class="button-right">点击进入 &gt;</div>
      </button>
    </div>
    <!-- 购物车部分 -->
    <div class="cart">
      <div class="cart-left">
        <div class="cart-left-icon" :style="totalQuantity == 0
          ? 'background-color:dimgray;'
          : 'background-color:#3190E8;'
          ">
          <i class="fa fa-shopping-cart"></i>
          <div class="cart-left-icon-quantity" v-show="totalQuantity != 0">
            {{ totalQuantity }}
          </div>
        </div>
        <div class="cart-left-info">
          <p>&#165;{{ totalPrice }}</p>
          <p>另需配送费{{ business.deliveryPrice }}元</p>
        </div>
      </div>
      <div class="cart-right" :style="totalSettle < business.starPrice
        ? 'background-color:dimgray;'
        : 'background-color:mediumseagreen;'
        ">
        <!-- 不够起送费 -->
        <div class="cart-right-item" v-show="totalSettle < business.starPrice"
          style="background-color: dimgray; cursor: default">
          &#165;{{ business.starPrice }}起送
        </div>
        <!-- 达到起送费 -->
        <div class="cart-right-item" @click="toOrder" v-show="totalSettle >= business.starPrice">
          去结算
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "BusinessInfo",
  data() {
    return {
      businessId: this.$route.query.businessId,
      business: {},
      foodArr: [],
      user: {},
      isMerchant: false, // 判断是否是商家
      showEditModal: false, // 控制编辑弹窗的显示
      currentEditItem: {}, // 当前编辑或添加的商品
      isEditing: false, // 区分是编辑还是添加模式
    };
  },
  created() {
    this.user = JSON.parse(sessionStorage.getItem("user"));
    // 检查用户身份
    if (this.user && this.user.usertype === "merchant") {
      this.isMerchant = true;
    }

    //根据businessId查询商家信息
    let url = "BusinessController/getBusinessById/" + this.businessId;
    this.$axios.get(url)
      .then((response) => {
        this.business = response.data.result;
      })
      .catch((error) => {
        console.error(error);
      });

    //根据businessId查询食品信息
    this.$axios.post('FoodController/listFoodByBusinessId', this.$qs.stringify({
      businessId: this.businessId
    })).then(response => {
      this.foodArr = response.data;
      for (let i = 0; i < this.foodArr.length; i++) {
        this.foodArr[i].quantity = 0;
      }

      if (this.user != null) {
        this.listCart();
      }
    }).catch(error => {
      console.error(error);
    });
  },

  methods: {
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    // 打开添加商品的窗口
    addNewProduct() {
      this.isEditing = false; // 切换为添加模式
      this.currentEditItem = {
        foodName: "",
        foodPrice: 0,
        foodExplain: "",
        foodImg: ""
      };
      this.showEditModal = true;
    },

    // 打开编辑商品的窗口
    editProduct(index) {
      const selectedItem = this.foodArr[index]; // 选择商品
      // 确保只有当前商家的商品可以被修改
      console.log('Selected Item Business ID:', selectedItem.businessId);
      console.log('Current Business ID:', this.businessId);
      if (selectedItem.businessId !== +this.businessId) {
        alert("您无权修改该商品");
        return;
      }

      this.isEditing = true; // 切换为编辑模式
      this.currentEditItem = { ...selectedItem }; // 当前编辑的商品
      this.showEditModal = true;
    },

    // 保存编辑商品
    saveProduct() {
       // 再次检查是否有权限修改该商品
      if (this.currentEditItem.businessId !== +this.businessId) {
        alert("您无权修改该商品");
        return;
      }

      let url = `FoodController/updateFood`;
      const updatedFoodData = {
        foodId: this.currentEditItem.foodId,
        foodName: this.currentEditItem.foodName,
        foodPrice: this.currentEditItem.foodPrice,
        foodExplain: this.currentEditItem.foodExplain,
        businessId: this.businessId, // 确保包含 businessId
        userId: this.user.userId  // 添加userId以验证是否为商家
      };

      this.$axios.post(url, updatedFoodData)
        .then((response) => {
          if (response.data.result == 1) {
            this.foodArr = this.foodArr.map(item => {
              if (item.foodId === this.currentEditItem.foodId) {
                return { ...this.currentEditItem };
              }
              return item;
            });
            this.showEditModal = false; // 关闭编辑窗口
          } else {
            alert("商品信息更新失败！");
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
    deleteProduct(foodId) {
      const selectedItem = this.foodArr.find(item => item.foodId === foodId);
      console.log('Selected Item Business ID:', selectedItem.businessId);
      console.log('Current Business ID:', this.businessId);
      if (selectedItem.businessId !== +this.businessId) {
        alert("您无权删除该商品");
        return;
      }

      let url = `FoodController/removeFoodByBusinessIdById`;
      this.$axios.post(url, {
        foodId: foodId,
        businessId: this.businessId
      })
        .then((response) => {
          if (response.data.result == 1) {
            this.foodArr = this.foodArr.filter(item => item.foodId !== foodId);
          } else {
            alert("删除商品失败！");
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
    // 保存新商品
    saveNewProduct() {
      let url = `FoodController/addFood`;
      const newFoodData = {
        foodName: this.currentEditItem.foodName,
        foodPrice: this.currentEditItem.foodPrice,
        foodExplain: this.currentEditItem.foodExplain,
        businessId: this.businessId, // 确保包含 businessId
        foodImg: this.currentEditItem.foodImg
      };

      this.$axios.post(url, newFoodData)
        .then((response) => {
          if (response.data.result == 1) {
            // 添加成功后将新商品加入到foodArr列表
            this.foodArr.push({ ...newFoodData, foodId: response.data.foodId });
            this.showEditModal = false; // 关闭添加商品窗口
          } else {
            alert("添加商品失败！");
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },

    // 取消操作
    cancelEdit() {
      this.showEditModal = false; // 关闭窗口
    },
    listCart() {
      let url = `CartController/listCart?userId=${this.user.userId}&businessId=${this.businessId}`;

      //let url =
      // "CartController/listCart/" + this.user.userId + "/" + this.businessId;
      this.$axios
        .get(url)
        .then((response) => {
          let cartArr = response.data.result;
          //遍历所有食品列表
          for (let foodItem of this.foodArr) {
            foodItem.quantity = 0;
            for (let cartItem of cartArr) {
              if (cartItem.foodId == foodItem.foodId) {
                foodItem.quantity = cartItem.quantity;
              }
            }
          }
          this.foodArr.sort();
        })
        .catch((error) => {
          console.error(error);
        });
    },
    add(index) {
      //商品数量++
      //首先做登录验证
      if (this.user == null) {
        this.$router.push({
          path: "/login",
        });
        return;
      }
      if (this.foodArr[index].quantity == 0) {
        //做insert
        this.savaCart(index);
      } else {
        //做update
        this.updateCart(index, 1);
      }
    },
    minus(index) {
      //首先做登录验证
      if (this.user == null) {
        this.$router.push({
          path: "/login",
        });
        return;
      }
      if (this.foodArr[index].quantity > 1) {
        //做update
        this.updateCart(index, -1);
      } else {
        //做delete
        this.removeCart(index);
      }
    },
    savaCart(index) {
      let url = `CartController/saveCart`;

      const cartData = {
        userId: this.user.userId,  // 用户ID
        businessId: this.businessId,  // 商家ID
        foodId: this.foodArr[index].foodId  // 食品ID
      };

      // 使用axios发送POST请求，携带JSON格式的请求体
      this.$axios
        .post(url, cartData)
        .then((response) => {
          if (response.data.result == 1) {
            // 成功添加后更新UI
            this.foodArr[index].quantity = 1;
            this.foodArr.sort();
          } else {
            alert("向购物车中添加食品失败！");
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },

    updateCart(index, num) {
      let url = `CartController/updateCart`;

      const cartData = {
        userId: this.user.userId,  // 用户ID
        businessId: this.businessId,  // 商家ID
        foodId: this.foodArr[index].foodId,  // 食品ID
        quantity: this.foodArr[index].quantity + num  // 更新后的商品数量
      };

      // 使用 POST 或 PUT 请求，并在请求体中发送 JSON 数据
      this.$axios.put(url, cartData)
        .then((response) => {
          if (response.data.result == 1) {
            this.foodArr[index].quantity += num;
            this.foodArr.sort();
          } else {
            alert("更新购物车数量失败！");
          }
        })
        .catch((error) => {
          console.error(error);
        });

    },
    removeCart(index) {
      let url = `CartController/removeCart`;

      const cartData = {
        userId: this.user.userId,
        businessId: this.businessId,
        foodId: this.foodArr[index].foodId
      };

      // 通过 DELETE 请求发送 JSON 数据
      this.$axios.delete(url, { data: cartData })
        .then((response) => {
          if (response.data.result == 1) {
            this.foodArr[index].quantity = 0;
            this.foodArr.sort();
          } else {
            alert("删除购物车商品失败！");
          }
        })
        .catch((error) => {
          console.error(error);
        });

    },
    toOrder() {
      this.$router.push({
        path: "/ordersPage",
        query: {
          businessId: this.business.businessId,
        },
      });
    },
    toBusinessInfo(businessId) {
      this.$router.push({
        path: "/businessInfo",
        query: {
          businessId: businessId,
        },
      });
    }
  },
  computed: {
    //食品总价格
    totalPrice() {
      let total = 0;
      for (let item of this.foodArr) {
        total += item.foodPrice * item.quantity;
      }
      return total;
    },

    //食品总数量
    totalQuantity() {
      let quantity = 0;
      for (let item of this.foodArr) {
        quantity += item.quantity;
      }
      return quantity;
    },

    //结算总价格
    totalSettle() {
      return this.totalPrice + Number(this.business.deliveryPrice);
    },
  }
}
</script>
<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  background-color: #f2f2f2;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: royalblue;

  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;

  display: flex;
  justify-content: center;
  align-items: center;

  color: white;
  font-size: 5vw;
  font-weight: 700;
}

/****************** 商家logo部分 ******************/
.wrapper .merchant-logo {
  width: 100%;
  padding-top: 15vw;
  display: flex;
  justify-content: center;
  margin-bottom: 3vw;
}

.wrapper .merchant-logo img {
  height: 35vw;
  width: 35vw;
  border-radius: 6vw;
}

/****************** 商家信息部分 ******************/
.wrapper .merchant-info {
  width: 100%;
  height: 20vw;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.wrapper .merchant-info h1 {
  color: black;
  font-size: 5.5vw;
  margin-bottom: 1.5vw;
}

.wrapper .merchant-info p {
  color: darkslategray;
  font-size: 3vw;
  margin-bottom: 1.5vw;
}

/****************** 食品列表部分 ******************/
.wrapper .food {
  width: 100%;
  /*使用下外边距避开footer部分*/
  /* margin-bottom: 14vw; */
}

.wrapper .food li {
  padding: 3vw;
  margin: 2vw;
  user-select: none;
  background-color: white;
  border-radius: 5vw;

  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .food li .left {
  display: flex;
  align-items: center;
}

.wrapper .food li .left img {
  width: 20vw;
  height: 20vw;
}

.wrapper .food li .left .left-info {
  margin-left: 3vw;
}

.wrapper .food li .left .left-info h3 {
  margin-bottom: 2vw;
  font-size: 4vw;
  color: darkslategray;
}

.wrapper .food li .left .left-info p {
  margin-bottom: 2vw;
  font-size: 3.5vw;
  color: gray;
}

.wrapper .food li .right {
  width: 16vw;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.wrapper .food li .right .fa-minus-circle {
  font-size: 4.5vw;
  color: gray;
  cursor: pointer;
}

.wrapper .food li .right .fa-plus-circle {
  font-size: 4.5vw;
  color: blue;
  cursor: pointer;
}

.wrapper .food li .right p {
  font-size: 3.5vw;
  color: darkslategray;
}

/****************** 购物车部分 ******************/
.wrapper .cart {
  width: 95%;
  height: 14vw;

  position: fixed;
  bottom: 3vw;
  left: 2.5%;

  display: flex;
}

.wrapper .cart .cart-left {
  background-color: dimgray;
  border-top-left-radius: 5vw;
  border-bottom-left-radius: 5vw;

  display: flex;
  flex: 2;
}

.wrapper .cart .cart-left .cart-left-icon .fa-shopping-cart {
  font-size: 8vw;
  color: white;
}

.wrapper .cart .cart-left .cart-left-icon {
  width: 14vw;
  height: 14vw;
  background-color: blue;
  border-radius: 10vw;
  border: solid 5px darkslategray;

  display: flex;
  justify-content: center;
  align-items: center;

  margin-top: -4vw;
  margin-left: 4vw;

  position: relative;
}

.wrapper .cart .cart-left .cart-left-icon-quantity {
  width: 5vw;
  height: 5vw;
  color: white;
  background-color: red;
  border-radius: 4vw;
  font-size: 3.5vw;

  display: flex;
  justify-content: center;

  position: absolute;
  right: -1.5vw;
  top: -1vw;
}

.wrapper .cart .cart-left .cart-left-info {
  margin-left: 1vw;

  display: flex;
  flex-direction: column;
}

.wrapper .cart .cart-left .cart-left-info p:first-child {
  font-size: 4.5vw;
  color: white;

  margin-top: 1vw;
}

.wrapper .cart .cart-left .cart-left-info p:last-child {
  font-size: 3vw;
  color: darkgray;
}

.wrapper .cart .cart-right {
  background-color: mediumseagreen;
  color: white;
  font-size: 4.7vw;
  font-weight: 700;
  border-top-right-radius: 5vw;
  border-bottom-right-radius: 5vw;

  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;

  cursor: pointer;
  user-select: none;
}

/*********推荐商家按钮*********/
.wrapper .merchant-button {
  width: 100%;
  box-sizing: border-box;
  padding: 4vw 10vw 22vw;
}

.wrapper .merchant-button button {
  width: 100%;
  height: 15vw;
  background-color: blue;
  border-radius: 5vw;

  display: flex;
  justify-content: space-between;
  align-items: center;

  color: white;
  border: none;
  outline: none;
}

.wrapper .merchant-button button .button-left {
  font-size: 3.5vw;
  margin-left: 4vw;
  align-items: center;
  user-select: none;
}

.wrapper .merchant-button button .button-right {
  font-size: 3.5vw;
  margin-right: 4vw;
  cursor: pointer;
}

/* 返回箭头的样式 */
.back-icon {
  font-size: 36px;
  /* 设置图标的大小 */
  position: fixed;
  /* 固定在页面上，不会随内容滚动 */
  top: 5px;
  /* 距离页面顶部 13px */
  left: 20px;
  /* 距离页面左侧 20px */
  color: #1a2edf;
  /* 设置图标的颜色 */
  cursor: pointer;
  /* 鼠标悬停时显示为手型 */
}

/* 编辑商品按钮 */
button {
  background-color: blue;
  color: white;
  padding: 1vw 3vw;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 10px;
}

button:hover {
  background-color: blue;
}

/* 编辑商品弹窗样式 */
.edit-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  width: 80%;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.modal-content h3 {
  font-size: 18px;
  margin-bottom: 10px;
}

.modal-content input,
.modal-content textarea {
  width: 100%;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.modal-content button {
  padding: 10px 20px;
  margin-right: 10px;
}
</style>